<template>
  <el-dialog v-model="state.isFalse" title="属性配置" :before-close="onVisable" :draggable="true" :width="750">
    <el-form ref="formRef" :model="state.dataForm" :rules="state.ruleList" label-width="150px">
      <el-form-item v-for="(v, i) in state.list.queryApi1" :key="i" :label="v.name" :prop="v.code">
        <el-input v-if="v.code!='dw'" size="large" v-model="state.dataForm[v.code]" placeholder="请输入"/>
        <el-select v-if="v.code=='dw'" size="large" v-model="state.dataForm.dw" placeholder="请选择" style="width:100%" clearable >
          <el-option v-for="(item, index) in state.dwList" :key="index" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="state.empty" class="f20 fw tc">请配置属性</div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" type="info" class="i23 bg-white" @click="onVisable">取 消</el-button>
        <el-button size="large" type="info" class="white bgi22" @click.stop="handleSubmit(formRef)">确 定</el-button>
        <el-button size="large" type="info" class="white bgi22" @click.stop="handleSync(formRef)">同 步</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import api from '../api'
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const state = reactive({
	  ...publicStore.$state,
    ruleList: [],
    dataForm: [],
    allFrom: [],
  })
  const props = defineProps({
    state: { 
      type: [Object, Array],
      default: ()=>{return {}}
    },
  })
  const emit = defineEmits(['init'])
  let formRef = ref()
  // 打开关闭弹窗
  const onVisable = async (val, type) => {
    state.isFalse = !state.isFalse
    if(!state.isFalse) return
    state.form = Object.assign({}, val)
    setInit()
  }

  const setInit = async() => {
    state.dataForm = []
    let query1 = {"o":"o_sensor_template_cfg_property","p":[state.form.type], "i":0}
    let query2 = {"o": "o_sensor_cfg_property",	"p": [state.form.id], "i": 0}
    let params = {queryApi1: query1, queryApi2: query2}
    state.list = await publicStore.post(params)
    state.empty = proxy.isNull(state.list.queryApi1)? true : false
    getAllFrom()
  }

  const getAllFrom = async() => {
    state.allFrom = []
    state.list.queryApi1.forEach((item, index)=>{ state.dataForm[item.code] = ''})
    Object.keys(state.dataForm).forEach((key, index)=>{
      let exist = state.list.queryApi2.find(a=>{return a.code == key})
      let from = {"o": "o_sensor_cfg_property", sensor_id: state.form.id, code: key}
      if(exist){
        from.a = '修改'
        from.t = 'upd'
        from.id = exist.id
        state.dataForm[key] = exist.value
        from.value = exist.value
      }else{
        from.a = '添加'
        from.t = 'add'
        from.id = new Date().getTime() + index
        state.dataForm[key] = ''
        from.value = state.dataForm[key] = ''
      }
      state.allFrom.push(from)
    })
  }

  // 提交
  const handleSubmit = (formEl) => {
    formEl.validate(valid => {
      Object.keys(state.dataForm).forEach((key, index)=>{
        state.allFrom[index].value = state.dataForm[key]
      })
      console.log('------', state.allFrom) 
      api.updateApi(state.allFrom).then((res:any) => {
        if(res.errcode == 0){
          ElNotification({ title: '提示', message: '操作成功', type: 'success' })
          emit('init', state.form[props.state.key])
          onVisable()
        }
      }).catch((err) => {
          ElNotification({ title: '提示', message: '操作失败', type: 'error' })
      })
    })
  }
  
  // 同步
  const handleSync = async(formEl) => {
    formEl.validate(valid => {
      if (valid) {
        ElMessageBox.confirm('是否确定同步到同类型设备?', '重要提示！', {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
          type: 'error'
        }).then(async() => {
          let sensorCfgList =  await getSensorCfg()
          let addFrom = await setAdd(sensorCfgList)
          let sensorCfgQuery =  await setSensorCfg(addFrom, sensorCfgList)
          console.log('------', sensorCfgQuery)
          api.updateApi(sensorCfgQuery).then((res) => {
          if(res.errcode == 0){
              ElNotification({ title: '提示', message: '同步成功', type: 'success' })
              emit('init', state.form[props.state.key])
              onVisable()
            }
          }).catch((err) => {
              ElNotification({ title: '提示', message: '同步失败', type: 'error' })
          })
        })
      }
    })
  }

  const setAdd = async(sensorCfgList) => {
    let tempArr = []
    let addFrom = {}
    props.state.list.map(async (item, index)=> {
      if(item.type == state.form.type) {
        Object.keys(state.dataForm).forEach((key, i)=>{
          let query = {"o": "o_sensor_cfg_property", "a": '同步', t: 'add', id: new Date().getTime() + index*10 + i, sensor_id: item.id, code: key, value: state.dataForm[key] }
          tempArr.push(query)
        })
      }
    })
    return tempArr
  }
  
  const getSensorCfg = async() => {
    let queryArr = []
    props.state.list.map(async item=> {
      if(item.type == state.form.type) {
        let query = {"o": "o_sensor_cfg_property", "i": 0,	"p": [item.id]}
        queryArr.push(query)
      }
    })
    let res = await publicStore.post({queryApi3: queryArr})
    return res
  }

  const setSensorCfg = async(addFrom, sensorCfgList) => {
    addFrom.map(async item=> {
      let exist = sensorCfgList.find(a=>{return a.sensor_id == item.sensor_id && a.code == item.code})
      if(exist){
        item.id = exist.id
        item.t = 'upd'
      }
    })
    return addFrom
  }

  // 暴露给父组件
  defineExpose({
    onVisable
  })
</script>

<style scoped lang="scss">

</style>
